Module pyglet.sprite

Display positioned, scaled and rotated images.

A sprite is an instance of an image displayed on-screen. Multiple sprites can display the same image at different positions on the screen. Sprites can also be scaled larger or smaller, rotated at any angle and drawn at a fractional opacity.

The following complete example loads a "ball.png" image and creates a sprite for that image. The sprite is then drawn in the window's draw event handler:

import pyglet

ball_image = pyglet.image.load('ball.png')
ball = pyglet.sprite.Sprite(ball_image, x=50, y=50)

window = pyglet.window.Window()

@window.event
def on_draw():
    ball.draw()

pyglet.app.run()

The sprite can be moved by modifying the x and y properties. Other properties determine the sprite's rotation, scale and opacity.

The sprite's positioning, rotation and scaling all honor the original image's anchor (anchor_x, anchor_y).

Drawing multiple sprites

Sprites can be "batched" together and drawn at once more quickly than if each of their draw methods were called individually. The following example creates one hundred ball sprites and adds each of them to a Batch. The entire batch of sprites is then drawn in one call:

batch = pyglet.graphics.Batch()

ball_sprites = []
for i in range(100):
    x, y = i * 10, 50
    ball_sprites.append(pyglet.sprite.Sprite(ball_image, x, y, batch=batch)

@window.event
def on_draw():
    batch.draw()

Sprites can be freely modified in any way even after being added to a batch, however a sprite can belong to at most one batch. See the documentation for pyglet.graphics for more details on batched rendering, and grouping of sprites within batches.

Since: pyglet 1.1

Classes

  SpriteGroup
Shared sprite rendering group.
  Sprite
Instance of an on-screen image.

Variables

  __package__ = 'pyglet'